#!/bin/sh
# date: 2022/11/22
# auth: frealess11
# desc: install prometheus
# doc: https://prometheus.io/docs/prometheus/latest/installation/#using-docker

# https://quay.io/repository/prometheus/prometheus
# https://prometheus.io/docs/prometheus/latest/installation/

ip_local=$(/usr/sbin/ip add | grep inet | grep global | grep -Ev 'docker' | awk '{print $2}' | awk -F/ '{print $1}' | tail -1)
port=9090
addr=${ip_local}:${port}
docker_name="prometheus_${port}"
image="prom/prometheus:v2.40.2"
conf=$(pwd)/conf
data=$(pwd)/data/prometheus/data

docker_start() {
  docker run -d --name=${docker_name} \
    --net=host \
    --restart=always \
    --log-opt max-size=100m \
    --log-opt max-file=10 \
    -m 2g \
    -v ${conf}:/etc/prometheus \
    -v ${data}:/prometheus/data \
    -u root \
    ${image} \
    --web.listen-address=0.0.0.0:9090 \
    --config.file=/etc/prometheus/prometheus.yaml \
    --storage.tsdb.path=/prometheus/data \
    --web.console.libraries=/etc/prometheus/console_libraries \
    --web.console.templates=/etc/prometheus/consoles \
    --web.enable-admin-api \
    --storage.tsdb.min-block-duration=2h \
    --storage.tsdb.max-block-duration=2h \
    --storage.tsdb.retention=1d \
    --web.enable-lifecycle \
    --log.level=info
}

docker_stop() {
  docker stop ${docker_name}
  docker rm ${docker_name}
}

docker_exec() {
  docker exec -it ${docker_name} sh
}

docker_logs() {
  docker logs --tail=10 ${docker_name}
}

# https://prometheus.io/docs/prometheus/latest/management_api/
prom_reload() {
  curl -XPOST http://${addr}/-/reload
}

# https://prometheus.io/docs/prometheus/latest/querying/api/
prom_targets() {
  curl -XGET "http://${addr}/api/v1/targets" | python -m json.tool
}

prom_metrics() {
  curl -XGET http://${addr}/api/v1/query?query=promhttp_metric_handler_requests_total | python -m json.tool
  # curl -XGET http://prometheus.oa.com/api/v1/query?query=http_requests_total{method="post"} | jq | more
}

usage() {
  if [ $# != 2 ]; then
    echo "usage: $0 $1 $msg"
    exit 1
  fi
}

case $1 in
start)
  docker_start
  ;;
stop)
  docker_stop
  ;;
exec)
  docker_exec
  ;;
logs)
  docker_logs
  ;;
reload)
  prom_reload
  ;;
targets)
  prom_targets
  ;;
metrics)
  prom_metrics
  ;;
*)
  echo "start|stop|exec|logs|reload|targets|metrics"
  ;;
esac
